/**
 * @description 本地储存管理
 */
export default class storage {

  /**
   * @description 设置缓存
   * @param key Key
   * @param value 值
   */
  public static setItem<T>(key: string, value: T, timeout?: number): void {
    if (!key) throw new Error('key 不能是null或空');
    if (isNaN(timeout || 0)) throw new Error('timeout 不是一个数字');

    const model = new storageModel();

    model.createtime = new Date().getTime();
    model.timeout = timeout || 0;
    model.value = value;

    localStorage.setItem(key, JSON.stringify(model));
  }

  /**
   * @description 获取缓存 
   * @param key 
   * @returns 
   */
  public static getItem<T>(key: string): T | null {
    if (!key) throw new Error('key 不能是null或空');

    let cache, data, now; 

    cache = localStorage.getItem(key);

    if (!cache) return null;

    data = JSON.parse(cache) as storageModel<T | null>;

    // 检查是否过期
    now = new Date().getTime();

    if (data.timeout > 0 && (now - data.createtime) / 1000 > data.timeout) {
      data.value = null;
      storage.removeItem(key);
    }

    return data.value;
  }

  /**
   * @description 移除缓存
   * @param key 
   */
  public static removeItem(key: string) {
    window.localStorage.removeItem(key);
  }

  /**
   * @description 清空缓存
   */
  public static clear() {
    window.localStorage.clear();
  }
}

/**
 * @description 本地储存数据结构
 */
class storageModel<T> {
  createtime!: number;
  timeout!: number;
  value!: T;
}